//
//  CRMDealDoneVC.m
//  New_Runway
//
//  Created by NewLife on 2018/3/1.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CRMDealDoneVC.h"
#import "CarSetListCell.h"
#import "CRMChooseCarVC.h"
#import "NRWCarCustomerIntentModel.h"
#import "PickDateView.h"
#import "NRWCarRemarkTextView.h"

@interface CRMDealDoneVC ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, PickerDateViewDelegate>

@end

NSInteger oneItemTag = 111;
NSInteger twoItemTag = 222;
NSInteger threeItemTag = 333;
NSInteger fourItemTag = 444;

@implementation CRMDealDoneVC
{
    UITableView *tableView;
    NRWCarRemarkTextView *remarkTextView;
    
    NSString *carId;
    NSString *carImageUrl;
    NSString *fixtureTime;
    NSString *earnest;//定金
    NSString *fixturePrice;//成交价格
    NSString *intentionId;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBarView.titleLabel.text = @"已成交";
    
    [self.navigationBarView setupRightItemTitle:@"确定"];
    
    [self setupTableView];
}

- (void)setupTableView {
    
    UITableViewController *tvc = [[UITableViewController alloc] init];
    [self addChildViewController:tvc];
    tableView = tvc.tableView;
    tableView.frame = CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH - self.BotH);
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = DPView();
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
}

- (void)rightItemClick {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if ([self checkDataValidity] == NO) {
        return;
    }
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    
    if (!isEmptyOrNilString(intentionId)) {
        [dictM setObject:intentionId forKey:@"intentionId"]; 
    }
    if (!isEmptyOrNilString(carId)) {//车辆ID
        [dictM setObject:carId forKey:@"carId"];
    }
    if (!isEmptyOrNilString(carImageUrl)) {//车辆图片
        [dictM setObject:carImageUrl forKey:@"fixtureCarPic"];
    }
    if (!isEmptyOrNilString(fixtureTime)) {//成交时间
        [dictM setObject:fixtureTime forKey:@"fixtureTime"];
    }
    if (!isEmptyOrNilString(earnest)) {//定金
        [dictM setObject:earnest forKey:@"earnest"];
    }
    if (!isEmptyOrNilString(fixturePrice)) {//成交价格
        [dictM setObject:fixturePrice forKey:@"fixturePrice"];
    }
    if (!isEmptyOrNilString([NRWCarUser sharedUser].userId)) {
        [dictM setObject:[NRWCarUser sharedUser].userId forKey:@"followerId"];
    }
    if (!isEmptyOrNilString([NRWCarUser sharedUser].userId)) {
        [dictM setObject:[NRWCarUser sharedUser].userName forKey:@"followName"];
    } 
    [dictM setObject:@50 forKey:@"followState"];
    [dictM setObject:@"已成交" forKey:@"followResult"];
    if (!isEmptyOrNilString(remarkTextView.text)) {
        [dictM setObject:remarkTextView.text forKey:@"followRemark"];
    } 
    if (!isEmptyOrNilString(self.customerShopId)) {
        [dictM setObject:self.customerShopId forKey:@"customerShopId"];
    } else {
        [SVProgressHUD showErrorWithStatus:@"customerShopId不能为空" dismissDelay:1];
        return;
    }
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",CRMContextApi, followAPI] refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] integerValue] == 1) {
            
            [SVProgressHUD showSuccessWithStatus:@"成交成功" dismissDelay:1 didDismiss:^{
               [self.navigationController safePopViewControllerWithClassName:@"CRMCustomerDetailVC"];
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"msg"] dismissDelay:1];
        }
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

        [SVProgressHUD dismiss];
    }];
}

- (BOOL)checkDataValidity {
    
    if (isEmptyOrNilString(carId)) {
        [ShowMessage showHintMessage:@"成交车辆不能为空!" duration:2.0 withRemindId:remindWarning];

        return NO;
    }
    if (isEmptyOrNilString(fixtureTime)) {
        [ShowMessage showHintMessage:@"成交时间不能为空!" duration:2.0 withRemindId:remindWarning];

        return NO;
    }
    if (isEmptyOrNilString(earnest)) {
        [ShowMessage showHintMessage:@"定金不能为空!" duration:2.0 withRemindId:remindWarning];

        return NO;
    }
    if (isEmptyOrNilString(fixturePrice)) {
        [ShowMessage showHintMessage:@"成交价格不能为空!" duration:2.0 withRemindId:remindWarning];

        return NO;
    }
    if (earnest.floatValue > fixturePrice.floatValue) {//定金大于成交价
        [ShowMessage showHintMessage:@"请输入正确的定金金额或成交价格!" duration:2.0 withRemindId:remindWarning];

        return NO;
    }
    return YES;
}

- (void)turnToChooseCarVC {
    
    CRMChooseCarVC *vc = [[CRMChooseCarVC alloc] init];
    vc.customerShopId = self.customerShopId;
    [self.navigationController pushViewController:vc animated:YES];
    
    __weak typeof(tableView)weakTableView = tableView;
    vc.chooseCarcompleted = ^(NRWCarCustomerIntentlListModel *model) {
      
        CarSetListCell *cell = [weakTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        cell.centerTF.text = model.carTitle;
        
        carId = model.carId;
        carImageUrl = model.carImageUrl;
        intentionId = model.intentionId;
    };
}

- (void)turnToChooseDateVC {
    
    PickDateView *pickerDate = [[PickDateView alloc]init];
    pickerDate.pickerViewHeight = 300;
    [pickerDate setIsShowDay:YES];//是否显示日信息
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 指定获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
    [pickerDate setDefaultTSelectYear:comp.year defaultSelectMonth:comp.month defaultSelectDay:comp.day];//设定默认显示的日期
    [pickerDate setDelegate:self];
    [pickerDate show];
}

- (void)pickerDateView:(BasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day {
    
    CarSetListCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    fixtureTime = [NSString stringWithFormat:@"%zd-%zd-%zd", year, month, day];
    cell.centerTF.text = fixtureTime;
}

- (void)centerTFTextDidChange:(UITextField *)sender {
    
    NSRange point1Range = [sender.text rangeOfString:@"."];
    NSRange point2Range = [sender.text rangeOfString:@"." options:NSBackwardsSearch];
    
    if (!NSEqualRanges(point1Range, point2Range)) {//不相等, 两个.
        
        sender.text = [sender.text substringToIndex:sender.text.length - 1];
    }
    
    if (sender.text.length > point1Range.location + point1Range.length + 2) {
        
        sender.text = [sender.text substringToIndex:point1Range.location + point1Range.length + 2];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CarSetListCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%zd",indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell = [[CarSetListCell alloc] initWithStyle:0 reuseIdentifier:[NSString stringWithFormat:@"%zd",indexPath.row]];
    }
    
    cell.switchButton.hidden = YES;
    cell._mySlider.hidden = YES;
    
    if (indexPath.row == 0) {
        
        cell.StarL.hidden = NO;
        cell.centerLabel.hidden = YES;
        cell.label.text = @"成交车辆";
        cell.centerTF.placeholder = @"请选择成交车辆";
        cell.centerTF.tag = oneItemTag;
        cell.centerTF.delegate = self;
    } else if (indexPath.row == 1) {
        
        cell.StarL.hidden = NO;
        cell.centerLabel.hidden = YES;
        cell.label.text = @"成交日期";
        cell.centerTF.placeholder = @"请选择成交日期";
        cell.centerTF.tag = twoItemTag;
        cell.centerTF.text = fixtureTime;
        cell.centerTF.delegate = self;
    } else if (indexPath.row == 2) {
        
        cell.StarL.hidden = NO;
        cell.centerLabel.hidden = YES;
        [cell.rightImage setImage:nil forState:UIControlStateNormal];
        [cell.rightImage setTitle:@"万元" forState:UIControlStateNormal];
        cell.label.text = @"定金";
        cell.centerTF.placeholder = @"请输入定金价钱";
        cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
        cell.centerTF.delegate = self;
        [cell.centerTF addTarget:self action:@selector(centerTFTextDidChange:) forControlEvents:UIControlEventEditingChanged];
        cell.centerTF.tag = threeItemTag;
    } else if (indexPath.row == 3) {
        
        cell.StarL.hidden = NO;
        cell.centerLabel.hidden = YES;
        [cell.rightImage setImage:nil forState:UIControlStateNormal];
        [cell.rightImage setTitle:@"万元" forState:UIControlStateNormal];
        cell.label.text = @"成交价格";
        cell.centerTF.placeholder = @"请输入成交价钱";
        cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
        cell.centerTF.delegate = self;
        [cell.centerTF addTarget:self action:@selector(centerTFTextDidChange:) forControlEvents:UIControlEventEditingChanged];
        cell.centerTF.tag = fourItemTag;
    } else if (indexPath.row == 4) {
        
        cell.centerTF.hidden = YES;
        cell.label.hidden = YES;
        cell.centerLabel.hidden = YES;
        cell.rightImage.hidden = YES;
        cell._mySlider.hidden = YES;
        cell.switchButton.hidden = YES;
        cell.picImage.hidden = YES;
        cell.StarL.hidden = YES;
        
        UILabel *remarkLabel = DPLabel()
        .setFont(kPingFangRegular13())
        .setTextColor(getColorFromString(@"323232"))
        .setText(@"备注");
        
        remarkTextView = [[NRWCarRemarkTextView alloc] initWithRemarkTextView];
        cell.contentView.addSubview(remarkLabel).addSubview(remarkTextView);
        
        [remarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView.mas_top).offset(12.5);
            make.left.equalTo(cell.contentView.mas_left).offset(15.5);
        }];
        
        [remarkTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(remarkLabel.mas_bottom).offset(11);
            make.left.equalTo(cell.contentView.mas_left).offset(16);
            make.right.equalTo(cell.contentView.mas_right).offset(-16);
            make.height.equalTo(@140);
        }];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 4) {
        return 180;
    }
    
    return 40;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if (textField.tag == oneItemTag) {
        
        [self turnToChooseCarVC];
        return NO;
    } else if (textField.tag == twoItemTag) {
        
        [self turnToChooseDateVC];
        return NO;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if (textField.tag == threeItemTag) {
        
        earnest = textField.text;
    } else if (textField.tag == fourItemTag) {
        
        fixturePrice = textField.text;
    } else if (textField.tag == twoItemTag) {
        
        fixtureTime = textField.text;
    }
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
